package com.example.smartmedicalsystem.service;

import com.example.smartmedicalsystem.entity.Medicine;
import com.example.smartmedicalsystem.repository.MedicineRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MedicineService {
    private final MedicineRepository medicineRepository;

    @Transactional
    public void deductStock(Long medicineId, int quantity) {
        Medicine medicine = medicineRepository.findById(medicineId)
                .orElseThrow(() -> new RuntimeException("药品不存在"));
        if (medicine.getStock() < quantity) {
            throw new RuntimeException(medicine.getName() + "库存不足");
        }
        medicine.setStock(medicine.getStock() - quantity);
        medicineRepository.save(medicine);
    }

    public List<Medicine> getAllMedicines() {
        return medicineRepository.findAll();
    }

    public Medicine getById(Long id) {
        return medicineRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("药品不存在"));
    }
}